//def maxseq(a: Array[Int]) = {
//  var maxsum = a(0)
//  var maxhere = a(0)
//
//  var i = 1
//  val len = a.length
//  while (i < len) {
//    maxhere = if (maxhere <= 0) a(i) else maxhere + a(i)
//
//    if (maxhere > maxsum) {
//      maxsum = maxhere
//    }
//
//    println(s"i: $i, maxhere: $maxhere, maxsum: $maxsum")
//    i += 1
//  }
//
//  maxsum
//}

val maxseq =
  (a: Iterable[Int]) =>
    a.tail.foldLeft((a.head, a.head)) {
      case ((prev, sum), n) =>
        val here = if (prev <= 0) n else prev + n
        (here, if (here > sum) here else sum)
    }._2

maxseq(Array(1, 2, 3, -4, 5, -6, -7, 2))
maxseq(Vector(-7, 1, -2, 3, -4, 5, -6, 2))
maxseq(List(-7, 1, -2, 3, -4, 5, -6, 2, -1, 3, -3, 1, 4))
